package com.woniu.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.woniu.entity.PageResult;
import com.woniu.entity.Result;
import com.woniu.entity.dto.ShopSearchDTO;
import com.woniu.mapper.ShopMapper;
import com.woniu.pojo.Shop;
import com.woniu.service.IShopService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author tarnett
 */
@Service
public class ShopServiceImpl implements IShopService {

    @Resource
    private ShopMapper shopMapper;

    @Override
    public PageResult<Shop> listSearch(ShopSearchDTO shopSearchDTO) {
        // 1. 开启分页
        PageHelper.startPage(shopSearchDTO.getCurrentPage(), shopSearchDTO.getPageSize());
        // 2. 调用mapper查询数据
        Page<Shop> page = shopMapper.listSearch(shopSearchDTO);
        // 3. 封装分页对象
        PageResult<Shop> pageResult = new PageResult<>();
        pageResult.setTotal(page.getTotal());
        pageResult.setData(page.getResult());
        // 4. 返回数据
        return pageResult;
    }

    @Override
    public Result save(Shop shop) {
        // 判断名称是否已经存在
        Shop shop1 = checkNameExist(shop.getName());
        if(shop1 != null){
            return Result.error("该名称已经存在");
        }
        return Result.commonByRow(shopMapper.save(shop));
    }

    @Override
    public Integer deleteByIds(Long[] ids) {
        return shopMapper.deleteByIds(ids);
    }

    @Override
    public Result updateById(Shop shop) {
        // 判断名称是否已经存在
        Shop shop1 = checkNameExist(shop.getName());
        if(shop1 != null && !shop1.getId().equals(shop.getId())){
            return Result.error("该名称已经存在");
        }
        return Result.commonByRow(shopMapper.updateById(shop));
    }

    @Override
    public Shop getById(Long id) {
        return shopMapper.getById(id);
    }

    @Override
    public Shop checkNameExist(String name) {
        return shopMapper.checkNameExist(name);
    }

    @Override
    public List<Shop> listAll() {
        return shopMapper.listAll();
    }
}
